#!/usr/bin/env bash

# 要检测的命令
checkCmd="java git mvn which"
# 要安装的软件
installDep="java-11*-devel git maven wget vim "
#要创建的用户
username="llww"
#要更改的环境变量文件
envFile="${HOME}/.bash_profile"
javaHome=""

LOCAL_IP=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")

show_red() {
  content=$1
  echo -e "\033[31m$content\033[0m"
}

show_green() {
  content=$1
  echo -e "\033[32m$content\033[0m"
}

envCheck() {
  env_name=$1
  show_green "---检查${env_name}环境"
  command -v java >/dev/null 2>&1
  if [[ $? != 0 ]]; then
    show_red "###无${env_name}环境"
  else
    show_green "###${env_name}环境存在"
  fi
}

envCheckFor() {
  for i in ${checkCmd}; do
    envCheck "$i"
  done
}

installEnv() {
  for i in ${checkCmd}; do
    yum -y install "$i"
  done

  for i in ${installDep}; do
    yum -y install "$i"
  done
}

createUser() {
  show_green "###创建 ${username} 用户"
  useradd llww
  echo "llww" | passwd --stdin llww
  show_green "###创建 ${username} 用户完成"
}

switchUser() {
  su ${username}
}

createPubKey() {
  show_green "###为${username} 创建公钥"
  expect <<EOF
spawn ssh-keygen -t rsa
expect {
"*id_rsa):" {
send "\n";
exp_continue
}
"*(y/n)?" {
send "y\n"
exp_continue
}
"*passphrase):" {
send "\n"
exp_continue
}
"*again:" {
send "\n"
}
}
expect eof
EOF

}

setJavaEnv() {
  if [ "${javaHome}" != "" ]; then
    echo "export JAVA_HOME=${javaHome}" >>${envFile}
    echo "export PATH=\${JAVA_HOME}/bin:$PATH" >>${envFile}
    echo "export CLASSPATH=.:\${JAVA_HOME}/lib/dt.jar:\${JAVA_HOME}/lib/tools.jar" >>${envFile}
    source ${envFile}
    java -version
    show_green 'JAVA环境变量配置成功......'
  fi

}

checkEnv(){
  if [ "${javaHome}" = "" ]; then
  show_green "javaHome 变量为空"
  show_green "检测yum 安装的jdk"
  openjdkCount=$(ls -lnt /usr/lib/jvm | grep drw | awk '{print $NF}' |wc -l)
  env=$(ls -lnt /usr/lib/jvm | grep drw | awk '{print $NF}')
  show_green "共发现${show_green}个jdk环境"
  show_green "${env}"
  default_jdk=$(ls -lnt /usr/lib/jvm | grep drw | awk '{print $NF}' | head -n 1)
  show_green "使用最新的${default_jdk}作为javaHome"
  javaHome=${default_jdk}
  fi
}

#envCheckFor
setJavaEnv
